<style type="text/css">
    #febs-user .eleTree-node-content:hover, .eleTree-node-content.eleTree-node-content-active {
        background-color: #ffffff !important;
        color: #1890ff; !important;
    }
    #febs-user .padding-15 {
        padding: 15px;
    }
</style>
<div class="febs-container">
    <div class="febs-body layui-fluid" id="febs-user" lay-title="用户管理">
        <div class="layui-row layui-col-space15 febs-full" style="margin: 0px -7.5px">
            <div class="layui-col-md3 layui-col-sm3 layui-col-xs6 febs-full" style="padding: 0px 7.5px">
                <div class="layui-card febs-full" th:classappend="${hasHeadCompanyRole } ? '' : 'padding-15'">
                    <form class="layui-form layui-table-form" lay-filter="tenant-form" id="tenant-form" th:if="${hasHeadCompanyRole}">
                        <div class="layui-row" style="padding: 15px;">
                            <div class="layui-form-item">
                                <div class="layui-col-md10 layui-col-sm12 layui-col-xs12">

                                    <label class="layui-form-label layui-form-label-sm" style="width: auto !important;">公司名称</label>
                                    <div class="layui-input-block" style="margin-left: 90px;">
                                        <select name="tenantSelect" id="tenantSelect" lay-search="" >
                                            <option th:each="tenant:${tenantList}" th:value="${tenant.tenantId}"
                                                    th:text="${tenant.tenantName}"></option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-col-md2 layui-col-sm12 layui-col-xs12">
                                    <div class="layui-btn layui-btn-primary table-action" style="margin-left: 5px;" id="queryTenantTree">
                                        <em class="layui-icon">&#xe848;</em>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                    <div class="eleTree deptTree" lay-filter="deptTree" style="margin-left: 1rem"></div>
                </div>
            </div>
            <div class="layui-col-md9 layui-col-sm9 layui-col-xs12 febs-full" style="padding: 0px 7.5px">
                <div class="layui-card febs-full">
                    <div class="layui-row" style="padding: 10px;">
                        <form class="layui-form layui-table-form" lay-filter="user-table-form">
                            <div class="febs-body-search">
                                <div class="layui-form-item">
                                    <div class="layui-inline">
                                        <label class="layui-form-label layui-form-label-sm">员工工号</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="userNo" autocomplete="off" class="layui-input">
                                            <input type="hidden" name="deptId" value="">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label layui-form-label-sm">员工账户</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="userName" autocomplete="off" class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label layui-form-label-sm">员工姓名</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="uname" autocomplete="off" class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label layui-form-label-sm">联系方式</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="mobile" autocomplete="off" class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label layui-form-label-sm">账户状态</label>
                                        <div class="layui-input-inline">
                                            <select name="status" lay-search="" >
                                                <option value="">请选择</option>
                                                <option value="0">禁用</option>
                                                <option value="1" selected>启用</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <div id="query" class="layui-btn layui-btn-normal">
                                            <i class="layui-icon">&#xe615;</i> 查询
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>
                        <div class="febs-table-full" style="margin: 0px;padding: 0px;">
                            <div style="margin: 15px 0px;">
                                <div id="add" class="layui-btn layui-btn-sm layui-btn-normal">
                                    <i class="layui-icon">&#xe654;</i> 新增
                                </div>
                                <div id="resetPw" class="layui-btn layui-btn-sm layui-btn-warm">
                                    <i class="layui-icon">&#xe79b;</i> 批量密码重置
                                </div>
                                <div id="export" class="layui-btn layui-btn-sm layui-btn-normal">
                                    <i class="layui-icon">&#xe7e4;</i> 导出Excel
                                </div>
                                <div id="selectUser" class="layui-btn layui-btn-sm layui-btn-normal">
                                    <em class="layui-icon">&#xe654;</em> 单选
                                </div>
                                <div id="selectUserList" class="layui-btn layui-btn-sm layui-btn-normal">
                                    <em class="layui-icon">&#xe654;</em> 多选
                                </div>
                            </div>
                            <table lay-filter="userTable" lay-data="{id: 'userTable'}"></table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/html" id="user-option">
    <span shiro:lacksPermission="user:update,user:delete">
        <span class="layui-badge-dot febs-bg-orange"></span> 无权限
    </span>
    <button type="button" class="layui-btn layui-btn-xs layui-btn-primary layui-border-orange"  lay-event="resetPassword" shiro:hasPermission="user:update">
        <i class="layui-icon layui-icon-refresh"></i>
        重置密码
    </button>
    <button type="button" class="layui-btn layui-btn-xs layui-btn-primary layui-border-orange"  lay-event="edit" shiro:hasPermission="user:update">
        <i class="layui-icon layui-icon-edit"></i>
        编辑
    </button>
    <button type="button" class="layui-btn layui-btn-xs layui-btn-primary layui-border-red"  lay-event="del" shiro:hasPermission="user:delete">
        <i class="layui-icon layui-icon-edit"></i>
        删除
    </button>
</script>
<script type="text/html" id="status">
    {{#  if(d.status==1){ }}
    <input type="checkbox" name="status" lay-skin="switch" checked lay-text="启用|禁用" value={{ d.id }}
           lay-filter="status">
    {{#  } else { }}
    <input type="checkbox" name="status" lay-skin="switch" lay-text="启用|禁用" value={{ d.id}}
           lay-filter="status">
    {{#  } }}
</script>
<script type="text/html" id="dept-leader">
    {{#
    var types = {
    "0": {title: '否'},
    "1": {title: '是'}
    };
    }}
    <span>{{ d.deptLeaderFlg ? types[d.deptLeaderFlg]['title'] : '' }}</span>
</script>
<script type="text/html" id="user-type">
    {{#
    var types = {
    "2": {title: '分支机构用户'},
    "1": {title: '机构用户'},
    "0": {title: '管理员用户'}
    };
    }}
    <span>{{ d.utype ? types[d.utype]['title'] : '' }}</span>
</script>

<script data-th-inline="javascript" type="text/javascript">
    layui.use(['dropdown', 'jquery', 'validate', 'laydate', 'eleTree', 'commonJS', 'form', 'table', 'febs'], function () {
        var $ = layui.jquery,
            laydate = layui.laydate,
            febs = layui.febs,
            form = layui.form,
            commonJS = layui.commonJS,
            table = layui.table,
            eleTree = layui.eleTree,
            _currentDeptData,
            $view = $('#febs-user'),
            $query = $view.find('#query'),
            $export = $view.find('#export'),
            $add = $view.find('#add'),
            $edit = $view.find('#edit'),
            $delete = $view.find('#delete'),
            $resetPw = $view.find('#resetPw'),
            $searchForm = $view.find('form'),
            sortObject = {field: 'createTime', type: null},
            $tenantSearchForm = $view.find('#tenant-form'),
            $queryTenantTree = $view.find('#queryTenantTree'),
            $resetTenantTree = $view.find('#resetTenantTree'),
            $tenantSelect = $tenantSearchForm.find('select[name="tenantSelect"]'),
            currentTenantId = [[${currentTenantId}]],
            hasHeadCompanyRole = [[${hasHeadCompanyRole}]],
            tableIns;

        let $selectUser = $view.find('#selectUser')
        let $selectUserList = $view.find('#selectUserList')


        $selectUser.on("click",function (){
            febs.modal.open('选择用户', 'common/user', {
                btn: ['确认','关闭'],
                area: $(window).width() <= 750 ? ['95%', '85%']: ['70%', '85%'],
                data:{
                    tenantId:'0',
                    multiple:false
                },
                yes: function (index, layero) {
                    let selectData = null
                   if(typeof getSelectData  === 'function'){
                       selectData = getSelectData()
                   }

                   console.log(JSON.stringify(selectData))
                    alert(JSON.stringify(selectData))
                    layer.close(index);
                },
                btn2: function (index, layero) {
                    layer.close(index);
                    return false;
                }
            });
        })

        $selectUserList.on("click",function (){
            febs.modal.open('选择用户', 'common/user', {
                btn: ['确认','关闭'],
                area: $(window).width() <= 750 ? ['95%', '85%']: ['70%', '85%'],
                data:{
                    tenantId:'0',
                    multiple:true,
                },
                yes: function (index, layero) {
                    let selectData = null
                    if(typeof getSelectData  === 'function'){
                        selectData = getSelectData()
                    }
                    console.log(JSON.stringify(selectData))
                    alert(JSON.stringify(selectData))
                    layer.close(index);
                },
                btn2: function (index, layero) {
                    layer.close(index);
                    return false;
                }
            });
        })

        form.render();
        //默认加载当前用户所属公司
        $tenantSelect.val(currentTenantId);
        form.render('select');

        initTable();


        // 状态 - 开关操作
        form.on('switch(status)', function(data){
            var status = data.elem.checked;
            var obj = {};
            obj.userId = data.value;
            if(!status){
                var title = '确定禁用吗？';
                obj.status = '0';
            }else{
                var title = '重新启用吗？';
                obj.status = '1';
            }
            layer.confirm(title,{icon:3,title:'提示'},function (index) {
                febs.post(ctx + 'user/updateStatus', obj, function () {
                    $('#febs-user').find('#query').click();
                });
                layer.close(index);
            },function (index) {
                //如果取消了的话，恢复原来的状态
                data.elem.checked = !data.elem.checked;
                form.render('checkbox');
            });
        });

        function initTable() {
            tableIns = febs.table.init({
                elem: $view.find('table'),
                id: 'userTable',
                url: ctx + 'user/list',
                height: getTableHeight(),
                skin: '',
                where:getQueryParams(),
                cols: [
                    [
                        {type: 'checkbox',width: 60,fixed:'left'},
                        {title: '序号', type: 'numbers',width: 60},
                        {field: 'tenantName', title: '所属公司',minWidth: 180 ,hide:!hasHeadCompanyRole},
                        {field: 'userNo',align:'center', title: '员工工号',width: 140 },
                        {field: 'userName', title: '员工账户',width: 140 },
                        {field: 'uname', title: '员工姓名',width: 140 },
                        {field: 'deptName', title: '所属部门',minWidth: 160 },
                        {field: 'userType', title: '员工类型', width: 90,align:'center',
                            templet: function (d) {
                                let returnText = "<span class='layui-badge febs-tag-gold'>未&nbsp;&nbsp;知</span>"
                                switch (d.userType){
                                    case "1":
                                        returnText = "<span class='layui-badge febs-tag-cyan'>本&nbsp;&nbsp;工</span>"
                                        break;
                                    case "2":
                                        returnText = "<span class='layui-badge febs-tag-volcano'>外包工</span>"
                                        break;
                                    case "3":
                                        returnText = "<span class='layui-badge febs-tag-green'>外协工</span>"
                                        break;
                                }
                                return returnText
                            }
                        },
                        {field: 'deptLeaderFlg', title: '部门主管', align:'center',width: 90,
                            templet: function (d) {
                                return d.deptLeaderFlg == '1' ? "<span class='layui-badge febs-tag-green'>是</span>":"<span class='layui-badge febs-tag-orange'>否</span>"
                            }
                        },
                        {field: 'mobile', title: '联系方式', width: 140},
                        {field: 'email', title: '联系邮箱', width: 180},
                        {field: 'status', title: '账户状态',align:'center',templet:'#status',width: 100 },
                        {title: '操作', align:'center',toolbar: '#user-option', width: 250,fixed:'right'}
                    ]
                ]
            });
        }

        laydate.render({
            elem: '#createTime',
            range: true,
            trigger: 'click'
        });

        table.on('tool(userTable)', function (obj) {
            var data = obj.data,
                layEvent = obj.event;
            if (layEvent === 'detail') {
                febs.modal.view('用户信息', 'system/webuser/detail/' + data.userName, {
                    area: [$(window).width() <= 750 ? '95%' : '50%','75%'],
                });
            }
            if (layEvent === 'del') {
                febs.modal.confirm('删除用户', '确定删除该用户？', function () {
                    deleteUsers(data.userId);
                });
            }
            if (layEvent === 'resetPassword') {
                febs.modal.confirm('重置密码', '确定重置密码？', function () {
                    var userIds = [];
                    userIds.push(data.userId)
                    resetPassword(userIds);
                });
            }
            if (layEvent === 'edit') {
                febs.modal.open('修改用户', 'system/user/update/' + data.userId, {
                    area: [$(window).width() <= 750 ? '95%' : '50%','75%'],
                    btn: ['提交', '取消'],
                    yes: function (index, layero) {
                        $('#user-update').find('#submit').trigger('click');
                    },
                    btn2: function () {
                        layer.closeAll();
                    },
                    data: {
                    }
                });
            }
        });

        table.on('sort(userTable)', function (obj) {
            sortObject = obj;
            tableIns.reload({
                initSort: obj,
                where: $.extend(getQueryParams(), {
                    field: obj.field,
                    order: obj.type
                })
            });
        });

        $query.on('click', function () {
         //   var params = $.extend(getQueryParams(), {field: sortObject.field, order: sortObject.type});
         //   tableIns.reload({where: params, page: {curr: 1}});
            reloadPage(1)
        });

        function reloadPage(curr) {
            tableIns.reload({where: getQueryParams(), page: {curr: curr}});
        }


        $export.on('click', function () {
            var params = $.extend(getQueryParams(), {field: sortObject.field, order: sortObject.type});
            febs.download(ctx + 'user/excel', params, '用户信息表.xls');
        });

        function tableReload(){
            $query.trigger('click');
        }

        function resetTableReload(){
            tableIns.reload({where: null, page: {curr: 1}});
        }

        $add.on('click', function () {
            if (_currentDeptData == undefined || _currentDeptData.length == 0) {
                febs.alert.warn('请先选择左侧机构中心！');
                return;
            }
            febs.modal.open('新增用户', 'system/user/add/'+_currentDeptData.tenantId, {
                btn: ['提交', '取消'],
                area: [$(window).width() <= 750 ? '95%' : '50%','75%'],
                yes: function (index, layero) {
                    $('#user-add').find('#submit').trigger('click');
                },
                btn2: function () {
                    layer.closeAll();
                },
                data: {
                    deptId: _currentDeptData.deptId,
                    deptName: _currentDeptData.deptName,
                    tenantId: _currentDeptData.tenantId,
                    tenantId: $tenantSelect.find('option:selected').val(),
                    tenantName: $tenantSelect.find('option:selected').text(),
                }
            });
        });

        $edit.on('click', function () {
            var checkStatus = table.checkStatus('userTable');
            if (checkStatus.data.length != 1) {
                febs.alert.warn('请选择一条需要修改的数据！');
            } else {
                var userId = checkStatus.data[0].userId;
                febs.modal.open('修改用户', 'system/user/update/' + userId, {
                    area: [$(window).width() <= 750 ? '95%' : '50%','75%'],
                    btn: ['提交', '取消'],
                    yes: function (index, layero) {
                        $('#user-update').find('#submit').trigger('click');
                    },
                    btn2: function () {
                        layer.closeAll();
                    },
                });
            }
        });

        $delete.on('click', function () {
            var checkStatus = table.checkStatus('userTable');
            if (!checkStatus.data.length) {
                febs.alert.warn('请选择需要删除的用户');
            } else {
                febs.modal.confirm('删除用户', '确定删除该用户？', function () {
                    var userIds = [];
                    layui.each(checkStatus.data, function (key, item) {
                        userIds.push(item.userId)
                    });
                    deleteUsers(userIds.join(','));
                });
            }
        });

        $resetPw.on('click', function () {
            var checkStatus = table.checkStatus('userTable');
            if (!checkStatus.data.length) {
                febs.alert.warn('请选择需要重置密码的用户');
            } else {
                var userIds = [];
                layui.each(checkStatus.data, function (key, item) {
                    userIds.push(item.userId)
                });
                resetPassword(userIds);
            }
        });

        function resetPassword(userIds){
            febs.post(ctx + 'user/password/reset/' + userIds.join(','), null, function () {
                febs.alert.success('所选用户密码已重置为系统默认密码');
            });
        }

        renderMenuTree();

        $resetTenantTree.on('click', function () {
            $tenantSelect.val(currentTenantId);
            $searchForm.find("input[name='deptId']").val('-1');
            form.render('select');
            resetTableReload();
            renderMenuTree();
        });

        $queryTenantTree.on('click', function () {
            tableReload();
            renderMenuTree();
        });
        function renderMenuTree() {
            eleTree.render({
                elem: '.deptTree',
                url: ctx + 'dept/tree',
                where: {
                    "invalidate_ie_cache": new Date()
                },
                accordion: false,
                highlightCurrent: true,
                renderAfterExpand: false,
                expandOnClickNode: false,
                checkOnClickNode: true,
                spread: true,
                defaultExpandAll:true,
                request: {
                    name: 'name',
                    key: "id",
                    checked: "checked",
                    data: 'data'
                },
                response: {
                    statusName: "code",
                    statusCode: 200,
                    dataName: "data"
                },
                where: {
                    "tenantId": $tenantSelect.val(),
                    "invalidate_ie_cache": new Date()
                },
                done: function (data) {
                    _currentDeptData = undefined;
                    //console.log(data)
                }
            });

            //return _menuTree;
        }

        eleTree.on("nodeClick(deptTree)", function (d) {
            var data = d.data.currentData.data;
            if (data.deptId != undefined && data.deptId != '0') {
                _currentDeptData = data;
                form.val("user-table-form", {
                    "deptId": data.deptId
                });
                $query.click();
            }

        });

        function getQueryParams() {
            var createTimeFrom,
                createTimeTo,
                createTime = $searchForm.find('input[name="createTime"]').val();
            if (createTime) {
                createTimeFrom = createTime.split(' - ')[0];
                createTimeTo = createTime.split(' - ')[1];
            }
            return {
                createTimeFrom: createTimeFrom,
                createTimeTo: createTimeTo,
                userNo: $searchForm.find('input[name="userNo"]').val()?.trim(),
                userName: $searchForm.find('input[name="userName"]').val()?.trim(),
                uname: $searchForm.find('input[name="uname"]').val()?.trim(),
                mobile: $searchForm.find("input[name='mobile']").val()?.trim(),
                deptId: $searchForm.find("input[name='deptId']").val(),
                tenantId: $tenantSelect.val(),
                status: $searchForm.find('select[name="status"]').val(),
                invalidate_ie_cache: new Date()
            };
        }

        function deleteUsers(userIds) {
            var currentUserId = currentUser.userId + '';
            if (('' + userIds).split(',').indexOf(currentUserId) !== -1) {
                febs.alert.warn('所选用户包含当前登录用户，无法删除');
                return;
            }
            febs.get(ctx + 'user/delete/' + userIds, null, function () {
                febs.alert.success('删除用户成功');
                $query.click();
            });
        }

        function getTableHeight() {
            return commonJS.calcTableHeight(60);
        }

        $(window).resize(function () {
            tableIns.reload({height: getTableHeight()});
        });
    })
</script>